Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
How to "attach" JSON to a button so that the data can be used when clicked on it

Using js, I make a request from which I get a json response. I loop through the list and add an html div for every object in the list. Each div contains elements that show a bit of info coming from that object (e.g. title, id, info, etc.). A button is also added to those divs that when clicked should make a request. The url that the request should be made to is in the json object for that div. See:

#json object for div
{
    "name":"Test1",
    "id":15,
    "link":"http://example.com"
}

#js to make div; object above is stored in obj
table = document.getElementById('div-list');

entry = document.createElement("div");
title = document.createElement("div");
title.innerHTML = obj.name;
entry.appendChild(title);

button = document.createElement("button");
button.innerHTML = 'Click me';
button.addEventListener("click", function() {
    data = {
        'id': [[  obj.id  ]]
    }
    fetch([[ obj.link ]], {
        method: 'POST',
        body: JSON.stringify(data)
    })
});
entry.appendChild(button);

table.appendChild(entry);

You can see the [[ obj.id|obj.link ]]. That is where the info from the json needs to go. However, doing obj.id or obj.link doesn't work because the function is run when clicked so the variable obj doesn't exist anymore. So I basically need to store the json in the entry-element so that when the button is clicked it can get it's info from somewhere.

I hopy you understand what I mean. Is there some way to allow that button-click-function access to "it's data" in order for it to determine where to send it's request to with what id?

about 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda